const Message = require("./modules/messageModule");
const Blog = require("../dao/modules/blogModule");
const { Op } = require("sequelize");

// 添加评论
const addComment = async (info) => {
  const { dataValues } = await Message.create(info);
  const id = dataValues.id;
  const data = await Message.findByPk(id, {
    include: [
      {
        model: Blog,
        as: "blog",
        attributes: ["title", "id"],
      },
    ],
  });

  return data.toJSON();
};

//删除评论
const deleteComment = async (id) => {
  const data = await Message.findByPk(id);
  await Message.destroy({
    where: {
      id,
    },
  });
  return data.toJSON();
};

//分页获取评论
const getCommentList = async (
  page = 1,
  limit = 10,
  keyword = "",
  blogId = -1
) => {
  let where = {};
  if (keyword.replace(/\s*/g, "").length !== 0) {
    where = {
      [Op.or]: [
        { nickname: { [Op.like]: `%${keyword}%` } },
        { content: { [Op.like]: `%${keyword}%` } },
      ],
    };
  }
  if (blogId > 0) {
    where.blogId = blogId; //获取对应文章评论
  } else {
    where.blogId = { [Op.ne]: null }; //获取所以评论
  }

  const { count, rows } = await Message.findAndCountAll({
    attributes: ["id", "nickname", "content", "createDate", "avatar"],
    where,
    offset: (page - 1) * limit,
    limit,
    include: [
      {
        model: Blog,
        as: "blog",
        attributes: ["title", "id"],
      },
    ],
    order: [["createDate", "DESC"]], //按时间降序，排序
  });
  const data = JSON.parse(JSON.stringify(rows));
  return {
    total: count,
    rows: data,
  };
};

//删除对应文章下的所有评论
const deleteBlogCommentAll = async (blogId) => {
  await Message.destroy({ where: { blogId } });
};

module.exports = {
  addComment,
  deleteComment,
  getCommentList,
  deleteBlogCommentAll,
};
